package com.itheima.redbaby.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.itheima.redbaby.BaseActivity;
import com.itheima.redbaby.GloableParams;
import com.itheima.redbaby.R;
import com.itheima.redbaby.BaseActivity.MyHttpTask;
import com.itheima.redbaby.activity.CartActivity.MyAdapter.HoldView;
import com.itheima.redbaby.bean.CartItem;
import com.itheima.redbaby.bean.CartProduct;
import com.itheima.redbaby.bean.CartProductScore;
import com.itheima.redbaby.bean.Product;
import com.itheima.redbaby.bean.ProductProperty;
import com.itheima.redbaby.dao.CartDao;
import com.itheima.redbaby.dao.domain.CartTable;
import com.itheima.redbaby.engine.impl.CartEngineImpl;
import com.itheima.redbaby.factory.DaoAndEngineFactory;
import com.itheima.redbaby.utils.ImageUtil;
import com.itheima.redbaby.utils.PromptManager;

public class CartModifyActivity extends BaseActivity implements OnClickListener{
	// 清空按钮
	private TextView shopcar_clear_text;
	// 确认修改按钮
	private TextView shopcar_confirm_text;
	//要修改的商品
	private ListView cart_modify_list;
	//数据库的库存量
	private List<CartProductScore>  serverscore;
	private Myadapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		init();
	}

	public void init() {
		setContentView(R.layout.shorpping_cart_modify_activity);
		shopcar_clear_text=(TextView) findViewById(R.id.shopcar_clear_text);
		shopcar_confirm_text=(TextView) findViewById(R.id.shopcar_confirm_text);
		cart_modify_list=(ListView) findViewById(R.id.cart_modify_list);
		
		shopcar_clear_text.setOnClickListener(this);
		shopcar_confirm_text.setOnClickListener(this);
		
		adapter = new Myadapter();
		if(GloableParams.isBottomEnter){
			//判断是否是从底部导航栏进入界面的
			GloableParams.isBottomEnter=false;
			getNativeCartData();
			
		}else{
			cart_modify_list.setAdapter(adapter);
		}
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.shopcar_clear_text:
			GloableParams.cartMap.clear();
			GloableParams.cartitemlist.clear();
			adapter.notifyDataSetChanged();
			CartDao nativeCartDao = DaoAndEngineFactory.getImpl(CartDao.class);
			nativeCartDao.delete();
			showCartNumber();
			break;

		case R.id.shopcar_confirm_text:
				//GloableParams.isBottomEnter=false;
				
				/*Intent intent=new Intent(CartModifyActivity.this,CartActivity.class);
				startActivity(intent);
			
				finish();*/
			Intent data=new Intent();
			data.putExtra("null", "ok");
			setResult(Activity.RESULT_OK, data);
			if(GloableParams.iscartactivity){
				GloableParams.iscartactivity=false;
				finish();
			}else{
				Intent intent=new Intent(CartModifyActivity.this,CartActivity.class);
				startActivity(intent);
			}
			showCartNumber();
			break;
		}
	}
	class Myadapter extends BaseAdapter{

		@Override
		public int getCount() {
			return GloableParams.cartitemlist.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			final HoldView holder =new HoldView();
			
			View v=View.inflate(getApplicationContext(), R.layout.shopcar_modify_cartitem, null);
				
				//holder.id=(TextView) v.findViewById(R.id.shopcar_item_prodId_text);
				holder.picpath=(ImageView) v.findViewById(R.id.shopcar_item_prodImage_img);
				holder.name=(TextView) v.findViewById(R.id.shopcar_item_prodName_text);
				holder.colorkey=(TextView) v.findViewById(R.id.shopcar_item_prodColor_key);
				holder.colorvalue=(TextView) v.findViewById(R.id.shopcar_item_prodColor_text);
				holder.sizekey=(TextView) v.findViewById(R.id.shopcar_item_prodSize_key);
				holder.sizevalue=(TextView) v.findViewById(R.id.shopcar_item_prodSize_text);
				holder.price=(TextView) v.findViewById(R.id.shopcar_item_prodPrice_text);
				holder.subtal=(TextView) v.findViewById(R.id.shopcar_item_subtotal_text);
				holder.num=(TextView)v.findViewById(R.id.shopcar_item_num_modify);
				holder.delete=(TextView) v.findViewById(R.id.shopcar_item_delete_modify);
				holder.score=(TextView) v.findViewById(R.id.summary_item_prodscore_min);
				v.setTag(holder);
				
				final CartItem cartItem = GloableParams.cartitemlist.get(position);
				final CartProduct product = cartItem.getProduct();
				List<ProductProperty> productPropertyList = product.getProductPropertyList();
				final int productprom = cartItem.getProductprom();
				
				//设置显示信息
				//holder.id.setText(product.getProduct_id());
				
				
				holder.name.setText(product.getName());
				holder.colorkey.setText(productPropertyList.get(0).getPkey());
				holder.colorvalue.setText(productPropertyList.get(0).getValue());
				holder.sizekey.setText(productPropertyList.get(1).getPkey());
				holder.sizevalue.setText(productPropertyList.get(1).getValue());
				holder.price.setText(product.getPrice()+"");
				holder.subtal.setText(product.getPrice()*productprom+"");
				holder.num.setText(productprom+"");
				ImageUtil.loadImageFromUrl(holder.picpath, product.getPicpath());
				
				/**
				 * 判断是否大于服务器库存，如果大于则显示缺货
				 */
				
				if(GloableParams.isBottomEnter){
					if(productprom>serverscore.get(position).getScorenum()){
						holder.score.setVisibility(View.VISIBLE);
					}
				}
				
				//设置按钮监听事件
				holder.delete.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						showCartNumber();
						if(GloableParams.cartitemlist.size()==0){
							GloableParams.cartMap.clear();
						}
						else{
							GloableParams.cartitemlist.remove(position);
							GloableParams.cartMap.put("cartitemlist", GloableParams.cartitemlist);
						}
						if(GloableParams.cartitemlist.size()==0){
							GloableParams.cartMap.clear();
						}
						adapter.notifyDataSetChanged();
						//System.out.println("点击了删除按钮");
						showCartNumber();
					}
				});
				holder.num.addTextChangedListener(new TextWatcher() {
					
					private int num;

					@Override
					public void onTextChanged(CharSequence s, int start, int before, int count) {
						//System.out.println("on");
						/**
						 * 小计跟着商品数量num变动
						 */
						String text = holder.num.getText().toString();
						num = Integer.parseInt(text);
						
						
					}
					
					@Override
					public void beforeTextChanged(CharSequence s, int start, int count,
							int after) {
						//System.out.println("before");
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void afterTextChanged(Editable s) {
						GloableParams.cartitemlist.get(position).setProductprom(num);
						GloableParams.cartMap.put("cartitemlist", GloableParams.cartitemlist);
						adapter.notifyDataSetChanged();
					}
				});
			
			return v;
		}
		class HoldView{
			TextView id;
			TextView name;
			TextView price;
			TextView subtal;
			TextView num;
			TextView colorkey;
			TextView colorvalue;
			TextView	sizekey;
			TextView  sizevalue;
			TextView delete;
			TextView score;
			ImageView picpath;
		}
		
	}
	private void getNativeCartData() {
		/**
		 * 获取本地购物车数据
		 */
		final Handler handler=new Handler(){
			@Override
			public void handleMessage(Message msg) {
				cart_modify_list.setAdapter(adapter);
			}
		};
		CartDao nativeCartData = DaoAndEngineFactory.getImpl(CartDao.class);
		final List<CartTable> nativeList = nativeCartData.findAll();
		new MyHttpTask() {
			protected void onPreExecute() {
				PromptManager.showProgressDialog(CartModifyActivity.this);
			};
			@Override
			protected Object doInBackground(Void... params) {
				if(nativeList.size()>0 && GloableParams.cartitemlist.size()!=0){
					
					StringBuilder sb=new StringBuilder();
					GloableParams.cartitemlist.clear();
					int totalCount=0;
					float totalPrice=0;
					float totalPoint=0;
					for(int i=0;i<nativeList.size();i++){
//						CartProduct product = GloableParams.cartitemlist.get(i).getProduct();
						CartTable cartTable = nativeList.get(i);
						
						//提取数据库的信息
						/*GloableParams.cartitemlist.get(i).setProductprom(nativeList.get(i).getProductprom());
						product.setProduct_id(cartTable.getProduct_id());
						product.setName(cartTable.getName());
						product.setPicpath(cartTable.getPicpath());
						product.setPrice(cartTable.getPrice());
						product.setScore(cartTable.getScore());
						product.setBuylimit(cartTable.getBuylimit());
						product.setIsgift(cartTable.getIsgift());*/
						CartProduct cartproduct=new CartProduct();
						List<ProductProperty> list=new ArrayList<ProductProperty>();
						ProductProperty productproperty=new ProductProperty();
						productproperty.setPkey("color");
						productproperty.setValue("red");
						list.add(productproperty);
						ProductProperty productproperty1=new ProductProperty();
						productproperty.setPkey("size");
						productproperty.setValue("M");
						list.add(productproperty1);
						
						cartproduct.setProduct_id(cartTable.getProduct_id());
						cartproduct.setName(cartTable.getName());
						cartproduct.setPicpath(cartTable.getPicpath());
						cartproduct.setPrice(cartTable.getPrice());
						cartproduct.setScore(cartTable.getScore());
						cartproduct.setBuylimit(cartTable.getBuylimit());
						cartproduct.setIsgift(cartTable.getIsgift());
						cartproduct.setProductPropertyList(list);
						
						int productprom=cartTable.getProductprom();
						CartItem cartitem=new CartItem();
						cartitem.setProduct(cartproduct);
						cartitem.setProductprom(productprom);
						GloableParams.cartitemlist.add(cartitem);
						//将获取的id装入容器
						if(i==nativeList.size()){
							sb.append(cartTable.getProduct_id());
						}else{
							sb.append(cartTable.getProduct_id()+",");
						}
						GloableParams.cartMap.put("cartitemlist", GloableParams.cartitemlist);
						totalCount+=productprom;
						totalPrice+=cartTable.getPrice()*cartTable.getProductprom();
						totalPoint+=cartTable.getScore();
					}
					GloableParams.cartMap.put("totalCount", totalCount);
					GloableParams.cartMap.put("totalPrice", totalPrice);
					GloableParams.cartMap.put("totalPoint", totalPoint);
					
					//发送id请求数据库存量
					CartEngineImpl cartEngineImpl=new CartEngineImpl();
					serverscore= cartEngineImpl.getCartJson(sb.toString());
					//System.out.println("kasjkfajslkdfjkas"+serverscore);
				}
				showCartNumber();
				
				return null;
			}
			protected void onPostExecute(Object result) {
				PromptManager.closeProgressDialog();
				handler.sendEmptyMessage(0);
			};
		}.executeHttp();
	}
}
